package com.wenjie.terminal.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;

import com.wenjie.terminal.config.App;
import com.wenjie.terminal.config.Common;
import com.wenjie.terminal.util.ConfigurationUtil;
import com.wenjie.terminal.util.UsbDeviceUtil;

/**
 * USB设备连接状态监听
 */
public class UsbDeviceReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        App app = (App) context.getApplicationContext();

        String action = intent.getAction();

        // 获取打印机配置
        ConfigurationUtil configurationUtil = app.getConfigurationUtil();
        int devicePid = configurationUtil.getInt(Common.PRINTER_PID, 0);
        int deviceVid = configurationUtil.getInt(Common.PRINTER_VID, 0);

        if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
            UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            if (device != null) {
                UsbDeviceUtil.addUsbDevice(app, device);

                if (devicePid != 0 && deviceVid != 0) {
                    if (device.getProductId() == devicePid && device.getVendorId() == deviceVid) {
                        app.setConfigPrinter(true);
                    }
                }
            }
        } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
            UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            if (device != null) {
                UsbDeviceUtil.removeUsbDevice(app, device);

                if (devicePid != 0 && deviceVid != 0) {
                    if (device.getProductId() == devicePid && device.getVendorId() == deviceVid) {
                        app.setConfigPrinter(false);
                    }
                }
            }
        }
    }
}